package com.joinway.framework.extension.net.mail;

import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailClient {

	protected String smtp;
	
	protected String user;
	
	protected String password;

	protected int port = 0;	// socket factory port
	
	protected int timeout = 30000;	// 30s
	
	public MailClient(String smtp, String user, String password){
		this.smtp = smtp;
		this.user= user;
		this.password = password;
	}

	public MailClient(String smtp, String user, String password, int port){
		this(smtp, user, password);
		this.port = port;
	}

	public MailClient(String smtp, String user, String password, int port, int timeout){
		this(smtp, user, password, port);
		this.timeout = timeout;
	}
	
//	public void sendTextMessage(String to, String subject, String content, String from) throws AddressException, MessagingException{
//		List<String> toList = new ArrayList<>();
//		toList.add(to);
//		sendTextMessage(toList, subject, content, from);
//	}

	public void sendTextMessage(String subject, String content, String...to) throws AddressException, MessagingException{
		sendTextMessage(Arrays.asList(to), subject, content);
	}
//	
//	public void sendTextMessage(List<String> to, String subject, String content) throws AddressException, MessagingException{
//		sendTextMessage(to, subject, content);
//	}
	
	public void sendTextMessage(List<String> to, String subject, String content) throws AddressException, MessagingException{
		Properties props = new Properties();
		props.put("mail.smtp.host", smtp);
		props.put("mail.smtp.auth", true);
		props.put("mail.stmp.timeout", timeout);
		
		if(port > 0){
			props.put("mail.stmp.socketFactory.port", port);
		}
		
		Session session = Session.getDefaultInstance(props);
		Message message = new MimeMessage(session);
		
		message.setFrom(new InternetAddress(user));
		
		for(String t : to){
			message.addRecipient(RecipientType.TO, new InternetAddress(t));
		}
		message.setSubject(subject);
		message.setText(content);
		message.saveChanges();
		
		Transport transport = session.getTransport("smtp");
		transport.connect(user, password);
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
	}
}
